<?php declare(strict_types=1);


namespace App\Api\V2\Controller\Lite;

use App\Api\Controllers\BaseController;
use App\Models\DeviceServiceProviders;
use App\Models\Store;
use App\Models\StoreAliyunAuth;
use App\Services\PengYiPeng\AliAppOauthService;
use App\Traits\ResponseTrait;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;
use Illuminate\Http\Request;
use BaconQrCode\Renderer\Image;


class OauthController extends BaseController
{
    use ResponseTrait;

    //商家单应用授权-生成二维码
    public function appAuth(Request $request): string
    {
        $provider_id = $request->post("provider_id");
        $provider = DeviceServiceProviders::query()->where(["id" => $provider_id])->first();
        if (empty($provider)) {
            return $this->errorResponse("服务商不存在");
        }
        $service = new AliAppOauthService();
        $type = $request->get("type", "MOBILE");
        $url = $service->getOauthUrl($provider->id, $type);
        try {
            //生成二维码文件
            $path = 'aliyunAuth/' . date("Y-m-d") . '/';
            $pathAbs = public_path($path);
            if (!is_dir($pathAbs)) {
                mkdir($pathAbs, 0777, true);
            }
            $renderer = new ImageRenderer(new RendererStyle(400), new Image\ImagickImageBackEnd());
            $writer = new Writer($renderer);

            $file_name = uniqid(date("YmdHis", time())) . "_" . rand(10000, 99999) . '.png';
            $file_path = $pathAbs . $file_name;
            $writer->writeFile($url, $file_path);
        } catch (\Exception $exception) {
            return $this->errorResponse($exception->getMessage());
        }
        return $this->successResponse("ok", ["data" => [
            "url" => $url,
            "path" => env("API_DOMAIN") . "/" . $path . $file_name
        ]]);
    }


}